﻿using System;
using System.Collections;
using System.Data;
using System.Web.UI.WebControls;

using BLL;
using Model;
using Utility;

namespace EvaluationSystem
{
    public partial class DimensionSet : System.Web.UI.Page
    {
        private const int POSITION_DEFAULT_TYPE = 0;//修改或者保存岗位默认维度
        private const int ACTIVITY_CUSTOM_TYPE = 1;//修改或者保存自定义活动维度

        private string _posID = string.Empty;//获取岗位ID,根据岗位ID得出岗位默认维度。
        private string _mode = string.Empty;//修改保存模式，上述两种类型
        private string _actID = string.Empty;//自定义的活动ID

        private const string DIM_SHCXX = "社会称许性";
        private const string DIM_CX = "诚信";
        private const string DIM_XLJKD = "心理健康度";


        private DimensionBLL _dimbll = new DimensionBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (Request["mode"] != null)
            {
                 _mode = Request["mode"].ToString();

                 if (!string.IsNullOrEmpty(_mode))
                 {
                     if (Int32.Parse(_mode) == POSITION_DEFAULT_TYPE)
                     {
                         ((SiteSystemMaster)Master).InitMenu();
                         ((SiteSystemMaster)Master).li3.Attributes.Add("class", "hover ccc");
                         ((SiteSystemMaster)Master).b_hmenu1.Style.Add("display", "none");
                         ((SiteSystemMaster)Master).b_hmenu2.Style.Add("display", "none");
                         ((SiteSystemMaster)Master).b_hmenu3.Style.Clear();
                         ((SiteSystemMaster)Master).s_menu3_1.Style.Add("COLOR", "#147ab8");
                         ((SiteSystemMaster)Master).s_menu3_1.Style.Add("TEXT-DECORATION", "none");

                         btnSetSameVal.Visible = false;
                        
                     }
                     else if (Int32.Parse(_mode) == ACTIVITY_CUSTOM_TYPE)
                     {
                         ((SiteSystemMaster)Master).InitMenu();
                         ((SiteSystemMaster)Master).li1.Attributes.Add("class", "hover ccc");
                         ((SiteSystemMaster)Master).b_hmenu1.Style.Clear();
                         ((SiteSystemMaster)Master).b_hmenu2.Style.Add("display", "none");
                         ((SiteSystemMaster)Master).b_hmenu3.Style.Add("display", "none");
                         ((SiteSystemMaster)Master).s_menu1_1.Style.Add("COLOR", "#147ab8");
                         ((SiteSystemMaster)Master).s_menu1_1.Style.Add("TEXT-DECORATION", "none");

                         btnSave.Attributes.Add("onclick", "return Check();");
                         btnSetSameVal.Attributes.Add("onclick", "return SetSameVal();");
                     }
                 }
            }

            /*判断是否是管理员身份*/
            if (Session["username"] == null)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", "<script>alert('请先登录系统!');top.location.href='../System/Login.aspx';</script>");
                return;
            }
            else
            {
                if (!IsPostBack)
                {
                    Bind();
                    LoadDimSelected();
                }
            }
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            foreach (GridViewRow row in grVDimensionSet.Rows)
            {
                string dimNM = row.Cells[2].Text.Trim();
                if (dimNM.Equals(DIM_SHCXX)||
                    dimNM.Equals(DIM_CX)||
                    dimNM.Equals(DIM_XLJKD))
                {
                    CheckBox chk = (CheckBox)row.Cells[0].FindControl("CB_Select");
                    chk.Checked = true; //社会称许性、诚信、心理健康 为默认维度
                    chk.Enabled = false;
                }

                if (dimNM.Equals(DIM_CX) || dimNM.Equals(DIM_XLJKD)||dimNM.Equals(DIM_SHCXX))
                {
                    if (row.FindControl("txtbEdit") != null)
                    {
                        ((TextBox)row.FindControl("txtbEdit")).Text = "0";
                        ((TextBox)row.FindControl("txtbEdit")).Enabled = false;
                    }
                }
            }
        }

        protected void CB_SelectAll_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < grVDimensionSet.Rows.Count; i++)
            {                
                GridViewRow gr = grVDimensionSet.Rows[i];
                if (!(gr.Cells[2].Text.Trim().Equals(DIM_SHCXX) ||
                      gr.Cells[2].Text.Trim().Equals(DIM_XLJKD) ||
                      gr.Cells[2].Text.Trim().Equals(DIM_CX)))
                {
                    CheckBox chk = (CheckBox)gr.Cells[0].FindControl("CB_Select");
                    chk.Checked = CB_SelectAll.Checked; //跟随全选按扭的状态变化;
                }
            }
        }

        private void LoadDimSelected()
        {
            if (Request["mode"] != null)
            {
                _mode = Request["mode"].ToString();

                if (!string.IsNullOrEmpty(_mode))
                {
                    if (Int32.Parse(_mode) == POSITION_DEFAULT_TYPE)
                    {
                        if (Request["posid"] != null)
                        {
                            _posID = Request["posid"].ToString();
                            PositionBLL pBll = new PositionBLL();

                            lblSpec.Text = "设置岗位默认维度: " + pBll.GetPositionNmById(Int32.Parse(_posID));
                            lblNotice.Text = string.Empty;
                            LoadDimension(_posID, 0);
                        }
                    }
                    else if (Int32.Parse(_mode) == ACTIVITY_CUSTOM_TYPE)
                    {
                        if (Request["actid"] != null)
                        {
                            _actID = Request["actid"].ToString();
                            ActivityBLL aBll = new ActivityBLL();
                            DataSet dsIncInfo = aBll.GetEUsrInfoByActivityId(Int32.Parse(_actID));
                            
                            lblSpec.Text = "当前公司名称:" +"["+
                                            dsIncInfo.Tables[0].Rows[0][1].ToString() +"]"+
                                            "  当前测评项目名称: " + "[" +
                                            aBll.GetActivityNM(Int32.Parse(_actID)) + "]";
                            
                            LoadDimension(_actID,1);
                            grVDimensionSet.Columns[5].Visible = true;
                        }
                    }
                    else
                    {
                    }
                }
            }
        }

        private void Bind()
        {
            DataSet ds = _dimbll.GetDimensionAll();
           
            //将三个特殊维度移动到上方。
            DataRow[] dr = ds.Tables[0].Select(@"dimension_name='" + DIM_SHCXX + 
                                                "' or dimension_name='" + DIM_XLJKD + 
                                                "' or dimension_name='" + DIM_CX + "'");

            if (dr != null && dr.Length == 3)
            {
                DataRow[] row = new DataRow[3];

                row[0] = ds.Tables[0].NewRow();
                row[1] = ds.Tables[0].NewRow();
                row[2] = ds.Tables[0].NewRow();

                row[0].ItemArray = dr[0].ItemArray;
                row[1].ItemArray = dr[1].ItemArray;
                row[2].ItemArray = dr[2].ItemArray;

                ds.Tables[0].Rows.InsertAt(row[0], 0);
                ds.Tables[0].Rows.InsertAt(row[1], 1);
                ds.Tables[0].Rows.InsertAt(row[2], 2);

                //删除三个特殊维度在维度得分表里。
                for (int s = 3; s < ds.Tables[0].Rows.Count; s++)
                {
                    if (ds.Tables[0].Rows[s]["dimension_name"].ToString().Trim().Equals(DIM_SHCXX) ||
                        ds.Tables[0].Rows[s]["dimension_name"].ToString().Trim().Equals(DIM_XLJKD) ||
                        ds.Tables[0].Rows[s]["dimension_name"].ToString().Trim().Equals(DIM_CX))
                    {
                        ds.Tables[0].Rows[s].Delete();
                        ds.Tables[0].AcceptChanges();
                        s--;
                    }
                }
            }

            grVDimensionSet.DataSource = ds.Tables[0];
            grVDimensionSet.DataSourceID = null;
            grVDimensionSet.DataBind();
            ds = null;
        }

        private void LoadDimension(string posID_or_actID, int mode)
        {
            if (string.IsNullOrEmpty(posID_or_actID))
            {
                return;
            }

            int rowNo = 0;
            DataSet ds = new DataSet();
            if (mode == POSITION_DEFAULT_TYPE)
            {
                ds = _dimbll.GetDefaultDimensionByPosID(posID_or_actID);
            }
            else if (mode == ACTIVITY_CUSTOM_TYPE)
            {
                ds = _dimbll.GetDimensionSetByActID(posID_or_actID);
            }

            if (ds == null || ds.Tables[0].Rows.Count <= 0) return;

            foreach (GridViewRow row in grVDimensionSet.Rows)
            {
                string hidecolumn = grVDimensionSet.DataKeyNames[0];
                int dimID = (int)grVDimensionSet.DataKeys[rowNo].Value;

                foreach (DataRow drow in ds.Tables[0].Rows)
                {
                    if (mode == POSITION_DEFAULT_TYPE)
                    {
                        //岗位默认维度不显示维度权重设置textbox，平分各个维度的权重
                        if (drow[0].ToString().Equals(dimID.ToString()))
                        {
                            ((CheckBox)row.FindControl("CB_Select")).Checked = true;
                        }
                    }
                    if (mode == ACTIVITY_CUSTOM_TYPE)
                    {
                        //活动设置维度时候，显示每个维度的权重
                        if (drow[1].ToString().Equals(dimID.ToString()))
                        {
                            ((CheckBox)row.FindControl("CB_Select")).Checked = true;
                            ((TextBox)row.FindControl("txtbEdit")).Text = drow["dimension_weight"].ToString();
                        }
                    }
                }
                rowNo++;
            }
        }

        private void SaveDimension(int mode)
        {
            int rowNo = 0;
            int rowSelected = 0;
            ArrayList dimIDArray = new ArrayList();

            if (POSITION_DEFAULT_TYPE == mode)//设置【岗位】的默认维度。
            {
                foreach (GridViewRow row in grVDimensionSet.Rows)
                {
                    int dimID = (int)grVDimensionSet.DataKeys[rowNo].Value;
                    CheckBox ck = (CheckBox)row.Cells[0].FindControl("CB_Select");
                    if (true == ck.Checked)
                    {
                        dimIDArray.Add(Int32.Parse(grVDimensionSet.DataKeys[rowNo].Value.ToString()));
                        rowSelected++;
                    }
                    rowNo++;
                }
                for (int i = 0; i < dimIDArray.Count; i++)
                {
                    Dimension dimTMP = _dimbll.GetDimension(dimIDArray[i].ToString());
                    string dimNM = dimTMP.Dimnm.Trim();

                    if (dimNM.Equals(DIM_SHCXX) || dimNM.Equals(DIM_XLJKD) || dimNM.Equals(DIM_CX))
                    {
                        _dimbll.SetPositionDimension(Int32.Parse(Request["posid"].ToString()),
                         Int32.Parse(dimIDArray[i].ToString()),
                         0);//社会称许性、心理健康度、诚信三个默认维度不计算权重。
                    }
                    else
                    {
                        _dimbll.SetPositionDimension(Int32.Parse(Request["posid"].ToString()),
                           Int32.Parse(dimIDArray[i].ToString()),
                           (float)(1.0 / (rowSelected - 3)));//减去三个特殊维度后，再平均。
                    }
                }
                MessageBox.ShowAndRedirect(this, "维度设置成功", "PositionList.aspx");
            }
            else if (ACTIVITY_CUSTOM_TYPE == mode)//设置【活动】的维度。
            {                
                //权重之和为1移交前台js检查->王聪慧2011.11.6
                //float dimWeightSum = 0;
                //foreach (GridViewRow r in grVDimensionSet.Rows)
                //{
                //    CheckBox ck = (CheckBox)r.Cells[0].FindControl("CB_Select");
                //    if (true == ck.Checked)
                //    {
                //        TextBox txt = (TextBox)r.Cells[5].FindControl("txtbEdit");
                //        dimWeightSum += float.Parse(string.IsNullOrEmpty(txt.Text) ? "0" : txt.Text);
                //    }
                //}
                //if (dimWeightSum != 1)
                //{
                //    MessageBox.ShowAndRedirect(this, "请确认所选维度的权重总和为1", "EnterpriseUserList.aspx");
                //    return;
                //}
                
                foreach (GridViewRow row in grVDimensionSet.Rows)
                { 
                    CheckBox ck = (CheckBox)row.Cells[0].FindControl("CB_Select");
                    if (true == ck.Checked)
                    {
                        TextBox txt = (TextBox)row.Cells[5].FindControl("txtbEdit");
                        _dimbll.SetActivityDimension(Int32.Parse(Request["actid"].ToString()),
                         int.Parse(grVDimensionSet.DataKeys[row.RowIndex].Values[0].ToString()),
                         float.Parse(txt.Text));
                    }
                }

                ActivityBLL aBll = new ActivityBLL();
                DataSet dsEUsrInfo = aBll.GetEUsrInfoByActivityId(Int32.Parse(Request.QueryString["actid"]));
                MessageBox.ShowAndRedirect(this, "维度设置成功", "ActivityList.aspx?users_id=" + dsEUsrInfo.Tables[0].Rows[0][0].ToString());
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            SaveDimension(int.Parse(Request["mode"].ToString()));
        }

        protected void GridView1_IndexChanging(object sender, GridViewPageEventArgs e)
        {
            grVDimensionSet.PageIndex = e.NewPageIndex;
            Bind();
            LoadDimSelected();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            if (Request["mode"] != null)
            {
                if (Int32.Parse(Request["mode"].ToString()) == POSITION_DEFAULT_TYPE)
                {
                    Response.Redirect("PositionList.aspx");
                }
                else
                {
                    Response.Redirect("EnterpriseUserList.aspx");
                }
            }
        }

        protected void btnSetSameVal_Click(object sender, EventArgs e)
        {

        }
    }
}